<template>
  <NSwitch :rail-style="railStyle" @update:value="handelChange" v-model:value="checked">
    <template #checked-icon>
      <n-icon>
        <MoonOutline />
      </n-icon>
    </template>
    <template #unchecked-icon>
      <n-icon>
        <SunnyOutline />
      </n-icon>
    </template>
  </NSwitch>
</template>
<script lang="ts" setup>
import { ref,onBeforeMount, type CSSProperties } from 'vue'
import { NSwitch, NIcon } from 'naive-ui'
import { MoonOutline, SunnyOutline } from '@vicons/ionicons5'
import storage from '@/utils/storage'
import ThemeUtils from '@/utils/ThemeUtils';
const railStyle = ({ focused, checked }: { focused: boolean; checked: boolean }) => {
  const style: CSSProperties = {}
  if (checked) {
    style.background = '#424245'
    if (focused) {
      style.boxShadow = '0 0 0 2px #424245'
    }
  } else {
    style.background = '#f4f4f4'

    if (focused) {
      style.boxShadow = '0 0 0 2px #f4f4f4'
    }
  }
  return style
}
const checked=ref(false)
const handelChange = (checked: Boolean) => {
  if (checked) {
    ThemeUtils.setTheme('dark')
  }
  else {
    ThemeUtils.setTheme('light')
  }
}
onBeforeMount(()=>{
  const themeLabel=storage.get('theme')
  if(themeLabel) {
    switch (themeLabel){
      case 'light':
        checked.value=false
        ThemeUtils.setTheme(themeLabel)
            break;
      case 'dark':
        checked.value=true
        ThemeUtils.setTheme(themeLabel)
            break;
      default:
        checked.value=false
        ThemeUtils.setTheme('light')
        throw new Error('storage theme error');
    }
  }
})
</script>
<style scoped></style>
